#include "../include/factory.hpp"
void factoryInit(process_data *, process_data *, client_t *)
{
}
void factoryStart(process_data *, process_data *)
{
}
int tcpInit(int *pSocketFd, FILE *fp)
{
    char buf[100], ip[30], port[30], *p;
    fgets(buf, 100, fp);
    p = buf;
    while (*p++ != '=')
        ;
    strcpy(ip, p);
    ip[strlen(ip) - 1] = 0;
    fgets(buf, 100, fp);
    p = buf;
    while (*p++ != '=')
        ;
    strcpy(port, p);
    port[strlen(port) - 1] = 0;
    int sockfd = 0;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(sockfd, -1, "socket");
    struct sockaddr_in ser;
    bzero(&ser, sizeof(ser));
    ser.sin_family = AF_INET;
    ser.sin_port = htons(atoi(port));
    ser.sin_addr.s_addr = inet_addr(ip);
    int on = 1;
    int ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    ERROR_CHECK(ret, -1, "setsockopt");
    ret = bind(sockfd, (struct sockaddr *)&ser, sizeof(ser));
    ERROR_CHECK(ret, -1, "bind");
    listen(sockfd, 100);
    *pSocketFd = sockfd;
    return 0;
}
void epoll_func(int epfd, int fd, int caozuo, int duxie)
{

    struct epoll_event event;
    event.events = duxie;
    event.data.fd = fd;
    epoll_ctl(epfd, caozuo, fd, &event);
}
int recvCYL(int fd, void *pbuf, int len)
{
    char *buf = (char *)pbuf;
    int total = 0, ret = 0;
    while (total < len)
    {
        ret = recv(fd, buf + total, len - total, 0);
        if (ret == 0)
        {
            return -1;
        }
        total += ret;
    }
    return 0;
}
int one_recv(int fd, Train_t *ptrain)
{
    int ret = recvCYL(fd, &ptrain->len, 4);
    ERROR_CHECK(ret, -1, "client quit");
    ret = recvCYL(fd, &ptrain->ctl_code, 4);
    ERROR_CHECK(ret, -1, "client quit");
    if (ptrain->len == 0)
    {
        return 0;
    }
    ret = recvCYL(fd, &ptrain->buf, ptrain->len);
    ERROR_CHECK(ret, -1, "client quit");
    return 0;
}